package com.cykj.page03.dao.impl;

import com.cykj.page03.dao.IUserDAO;
import com.cykj.page03.entity.StudentDO;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @BelongsProject: HandTomcat
 * @BelongsPackage: com.cykj.page03.dao.impl
 * @Author: WWJ
 * @CreateTime: 2025-06-19 00:17
 * @Description: 操作数据库在这里操作
 * @Version: 1.0
 */
public class UserDaoImpl implements IUserDAO {
    @Override
    public StudentDO login(String account, String password) {
        try {
            //1.导入jar包
            //2.加载数据库驱动    注册到DriverManager中
            Class.forName("com.mysql.cj.jdbc.Driver");
            //3.获取数据库连接对象
            Connection conn = DriverManager.getConnection(
                    "jdbc:mysql://127.0.0.1:3306/jx2503_02",
                    "root",
                    "root");
            //4.定义sql语句，使用？占位符防止SQL注入
            String sql = "select * from user where account = ? and password =?";
            //5.创建预处理对象
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,account);
            ps.setString(2,password);
            //执行sql语句，获取结果集
            ResultSet rs = ps.executeQuery();
            if (rs.next()){
                //创建实体类对象并封装结果
                System.out.println("进来这");
                StudentDO studentDO = new StudentDO();
                studentDO.setName(rs.getString("name"));//从结果集中获取name字段
                return studentDO;
            }
            rs.close();
            ps.close();
            conn.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("数据库无");
        return null;//查询不到返回null
    }

//    @Override
//    public Integer enroll(String account, String password, String name) {
//        try {
//            Class.forName("com.mysql.cj.jdbc.Driver");
//            Connection conn = DriverManager.getConnection(
//                    "jdbc:mysql://127.0.0.1:3306/jx2503_02",
//                    "root",
//                    "root");
//            String sql = "insert into user (account,password,name) values(?,?,?)";
//            PreparedStatement ps = conn.prepareStatement(sql);
//            ps.setString(1, account);
//            ps.setString(2, password);
//            ps.setString(3, name);
//            int res = ps.executeUpdate();
//            ps.close();
//            conn.close();
//            return res;
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//    }
}
